package ldapmodel

import (
	"crypto/tls"
	"fmt"
	"github.com/go-ldap/ldap/v3"
)

func LdapAuth(username,password string) bool {
	l, err := ldap.Dial("tcp", "IP:PORT")
	if err != nil {
		fmt.Println(err)
		return false
	}
	err = l.StartTLS(&tls.Config{InsecureSkipVerify: true})
	if err != nil {
		fmt.Println(err)
		return false
	}
	err = l.Bind("cn=root,dc=xxxx,dc=com", "xxxxxxx")
	if err != nil {
		fmt.Println(err)
		return false
	}
	sql := ldap.NewSearchRequest("dc=xxxx,dc=com",
		ldap.ScopeWholeSubtree,
		ldap.NeverDerefAliases,
		0,
		0,
		false,
		//"(&(objectClass=organizationalPerson))",   // 查询所有人
		fmt.Sprintf("(&(objectClass=Person)(cn=%s))", username),
		[]string{"cn", "cn"}, nil)
	cur, err := l.Search(sql)
	if err != nil {
		fmt.Println(err)
		return false
	}
	if len(cur.Entries) == 1 {
		userdcur := cur.Entries[0].DN
		err = l.Bind(userdcur, password)
		if err != nil {
			fmt.Println(username, err)
			return false
		} else {
			fmt.Println("登陆成功")
			return true
		}
	} else {
		return false
	}
}
